/* Gauge - Performance Measurement Framework for Mobile Platforms
 * Copyright (C) 2013, Juha Hytonen <juha.a.hytonen@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.gauge;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Manages a file and provides an interface for writing into it.
 */
public final class FileManager {

	private File file;
	private FileWriter writer;
	
	public FileManager(File file) throws Exception {
		this.file = file;
		createFile();
		testIfFileCanBeWrittenInto();
		createFileWriter();
	}
	
	private void createFile() throws Exception {
		if (!file.createNewFile()) {
			throw new Exception("Could not create file " + file.getName());
		}
	}
	
	private void testIfFileCanBeWrittenInto() throws Exception {
		if(!file.canWrite()) {
			throw new Exception("Can not write to file " + file.getName());
		}
	}
	
	private void createFileWriter() throws Exception {
		writer = new FileWriter(file);
	}
	
	/**
	 * Writes given line into the file. Line break is automatically appended.
	 */
	public void WriteLine(String line) throws Exception {
		try {
			writer.write(line);
			writer.write('\n');
		} 
		catch (IOException e) {
			throw new Exception("Could not write to file " + file.getName());
		}
	}
	
	/**
	 * Writes given data into the file. No line break is appended.
	 */
	public void Write(String data) throws Exception {
		try {
			writer.write(data);
		} 
		catch (IOException e) {
			throw new Exception("Could not write to file" + file.getName());
		}
	}
	
	/**
	 * Effectively saves the file on disk. No further writes are possible.
	 */
	public void Close() throws Exception {
		try {
			writer.flush();
			writer.close();
		} 
		catch (IOException e) {
			throw new Exception("Could not save file " + file.getName());
		}
	}

}
